package view.Etudiants.Page;

import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import java.util.ArrayList;

import javax.swing.JPanel;
import javax.swing.JTree;
import javax.swing.event.TreeSelectionEvent;
import javax.swing.event.TreeSelectionListener;
import javax.swing.tree.DefaultMutableTreeNode;
import javax.swing.tree.TreeSelectionModel;

import Controller.EtudiantController;
import Model.Exercice;

import view.Fenetre;

@SuppressWarnings("serial")
public class ArboPanel extends JPanel implements MouseListener, TreeSelectionListener {

	private JTree tree;

	public ArboPanel(String theme) {

		EtudiantController cEtud = Fenetre.control.getEtudiantController();

		// Creation d'un vecteur d'objets Exercice
		ArrayList<Exercice> liste = cEtud.getProfesseur().getExercices(theme);

		// Creation de l'arbre
		DefaultMutableTreeNode root = new DefaultMutableTreeNode();			// racine
		DefaultMutableTreeNode node = null;									// noeud
		tree = null;

		// Creation de l'arborescence
		for (int i=0; i<liste.size(); i++) {

			// Affichage du theme sur le noeud principal
			node = new DefaultMutableTreeNode(liste.get(i));
			//node.setUserObject(liste.get(i).getTitre());

			root.add(node);
		}

		// Creation de l'arbre a partir du noeud principal
		tree = new JTree(root);

		// Ajout de la transparence
		tree.setOpaque(false);

		// Masquage de la racine
		tree.setRootVisible(false);


		tree.getSelectionModel().setSelectionMode(TreeSelectionModel.SINGLE_TREE_SELECTION);

		// Ajout de l'arbre
		this.add(tree);

		// Ajout des ecouteurs
		tree.addMouseListener(this);

	}

	@Override
	public void mousePressed(MouseEvent event) 
	{
		int selRow = tree.getRowForLocation(event.getX(), event.getY());
		tree.getPathForLocation(event.getX(), event.getY());

		if (selRow != -1) {

			if (event.getClickCount() == 2) {

				DefaultMutableTreeNode node = (DefaultMutableTreeNode)
				tree.getLastSelectedPathComponent();

				if (node == null) {
					return;
				}

				Object nodeInfo = node.getUserObject();

				if (node.isLeaf()) {

					Exercice ex = (Exercice) nodeInfo;
					EtudPage.center.update(ex.getRempliPanel(Fenetre.control));

				}
			}
		}
	}

	@Override
	public void mouseClicked(MouseEvent event) {}
	@Override
	public void mouseEntered(MouseEvent event) {}
	@Override
	public void mouseExited(MouseEvent event) {}
	@Override
	public void mouseReleased(MouseEvent event) {}
	@Override
	public void valueChanged(TreeSelectionEvent event) {}

}
